package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Order(1)
@Component
@WebFilter(value = "wmTokenFilter",urlPatterns = "/*")
public class WmTokenFilter extends GenericFilter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.获取请求对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //2.获取请求头中的userId
        String userId = httpServletRequest.getHeader("userId");
        if (StringUtils.isNotBlank(userId)) {
            // 存在则放入到thread local中
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(wmUser);
        }
        //3.放行请求
        chain.doFilter(request,response);
        //4.清除thread local中的信息
        WmThreadLocalUtils.clear();
    }
}
